<template>
	<div class='manage-project'>
		<el-header>
			<h2>项目管理</h2>
			<el-button type="primary" @click="onAddProject">添加项目</el-button>
		</el-header>
		<el-main>
			<template v-if="projectList?.length">
				<div class="pro-card" v-for="item in projectList" :key="item._id" @click="onClick(item)">
					<el-space :size="2" @click.stop>
						<el-icon @click.stop="onEdit(item)">
							<Edit />
						</el-icon>
						<el-icon @click.stop="onDelete(item)">
							<Delete />
						</el-icon>
					</el-space>
					<div>{{ item.name }}</div>
					<div>{{ item.code }}</div>
					<div>{{ dayjs(item.createTime).format('YYYY-MM-DD') }}</div>
				</div>
			</template>
			<el-empty v-else description="暂无数据" :image-size="100" />
		</el-main>
		<ModalProject v-model="showProjectModal" :editData="editData" :is-edit="isEdit" @save-success="getProjectList">
		</ModalProject>
	</div>
</template>

<script setup lang="ts">
import { ElMessageBox, ElMessage } from 'element-plus';
import { Edit, Delete } from '@element-plus/icons-vue'
import ModalProject from './ModalProject/index.vue';
import { queryProject, deleteProject, type ProjectItem } from '@/api/projectList';
import { useRouter } from 'vue-router';
import { useMainStore } from '@/stores';
import dayjs from 'dayjs';
import { ref } from 'vue';

const router = useRouter();
const store = useMainStore();
const showProjectModal = ref(false);
const isEdit = ref(false);
const projectList = ref<Array<ProjectItem>>([]);
const editData = ref<ProjectItem | null>(null);

const onAddProject = () => {
	isEdit.value = false;
	editData.value = null;
	showProjectModal.value = true;
}
const onEdit = (item: ProjectItem) => {
	isEdit.value = true;
	editData.value = item;
	showProjectModal.value = true;
}
const onDelete = (item: ProjectItem) => {
	console.log(`output->item`, item)
	ElMessageBox.confirm(
		'此操作将永久删除数据，是否继续?',
		'提示',
		{
			confirmButtonText: '删除',
			cancelButtonText: '取消',
			type: 'error',
		}
	)
		.then(() => {
			deleteProject([item._id]).then(() => {
				ElMessage.success('删除成功')
				getProjectList()
			})
		})
		.catch(() => {
			ElMessage.info('再想想吧~')
		})
}
const onClick = (item: ProjectItem) => {
	store.setProjectInfo(item);
	router.push('./manage-data-structure')
}
const getProjectList = () => {
	queryProject().then(res => {
		projectList.value = res;
	})
}
getProjectList()
</script>
<style lang='scss' scoped>
@import './index';
</style>
